package com.zcoj.util;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @method: []
 * @param:
 * @returns: 相似度检测
 * @description:
 * @author: chen.bin
 * @version: 1.0.0
 * @date 2023/5/7 22:41
 **/
@Component
public class CosineSimilarity {
    public  double cosineSimilarity(String text1, String text2) {
        Map<String, Integer> vector1 = codeToVector(text1);
        Map<String, Integer> vector2 = codeToVector(text2);

        double dotProduct = 0.0;
        double norm1 = 0.0;
        double norm2 = 0.0;

        for (String key : vector1.keySet()) {
            if (vector2.containsKey(key)) {
                dotProduct += vector1.get(key) * vector2.get(key);
            }
            norm1 += vector1.get(key) * vector1.get(key);
        }

        for (String key : vector2.keySet()) {
            norm2 += vector2.get(key) * vector2.get(key);
        }

        return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
    }

    private static Map<String, Integer> codeToVector(String code) {
        String[] words = code.split("\\W+");
        Map<String, Integer> vector = new HashMap<>();

        for (String word : words) {
            if (vector.containsKey(word)) {
                vector.put(word, vector.get(word) + 1);
            } else {
                vector.put(word, 1);
            }
        }

        return vector;
    }

//    public static void main(String[] args) {
//        String code1 = "{chenbin,xuanhuiru}";
//        String code2 = "{chenbin xuanhuiru}";
//        CosineSimilarity cosineSimilarity = new CosineSimilarity();
//        double similarity = cosineSimilarity.cosineSimilarity(code1, code2);
//        System.out.println("Similarity: " + similarity);
//    }
}
